<template>
  <div class="page-miH page-bgBack">
    <a-layout>
      <a-row class="head">
        <div @click="goBack" style="cursor: pointer">
          <a-icon type="left" />
          <div class="left2">返回</div>
        </div>
        <a-col class="title">
          <strong>编辑工资表模板</strong>
        </a-col>
      </a-row>
      <a-row class="describeHead">
        <a-col>
          <span class="title">使用指南</span>
        </a-col>
        <a-col style="margin-top: 13px">
          <span class="font"> 设置工资表模板，即对应企业计薪时的月工资表头项目。每位员工只适用一个模板。 </span>
        </a-col>
        <a-divider />
      </a-row>
      <a-row class="inputBox">
        <a-col> <div class="inpputBoxTitle">模板名称</div></a-col>
        <a-col style="margin-top: 15px">
          <a-input v-model="inputName" placeholder="请输入" style="width: 337px" :disabled="inputName === '默认模板'" />
        </a-col>
      </a-row>
      <a-row class="content">
        <div>
          <div class="flexBoxTitle"><span>项目模板设置</span></div>
          <div style="width: 100%; display: flex; justify-content: space-between">
            <div class="little">设置此工资表模板参与计薪的项目。您可以新增或移除工资表模板的项目</div>
            <a-button class="primaryButton" type="primary" @click="handleClick"> <a-icon type="plus" />新增项目 </a-button>
          </div>
        </div>
        <a-col>
          <a-col style="margin-top: 8px; margin-bottom: 24px">
            <div style="display: flex; align-items: center">
              <div style="font-size: 14px; font-weight: 400; color: #55565d">尾数处理(四舍五入)</div>
              <a-select v-model="decimalPlaces" placeholder="请选择" style="width: 300px; margin-left: 12px">
                <a-select-option :value="0">
                  保留为整数
                </a-select-option>
                <a-select-option :value="1">
                  保留到小数点后1位
                </a-select-option>
                <a-select-option :value="2">
                  保留到小数点后2位
                </a-select-option>
                <a-select-option :value="3">
                  保留到小数点后3位
                </a-select-option>
                <a-select-option :value="4">
                  保留到小数点后4位
                </a-select-option>
              </a-select>
            </div>
          </a-col>
          <a-table :columns="columns" :pagination="false" row-key="id" :data-source="dataList" :loading="loading">
            <div slot="name" slot-scope="text">
              {{ text }}
              <a-tooltip v-if="text === '定薪工资'">
                <template slot="title">
                  定薪工资:<br />是该员工定薪项目的合计（基本工资、各种补贴等）该项数值将自动从员工薪资档案中获取
                </template>
                <a-icon type="question-circle" />
              </a-tooltip>
            </div>
            <div slot="isAdd" slot-scope="text">
              <span v-if="text === 0">非工资计算项</span>
              <span v-if="text === 1">工资增加项</span>
              <span v-if="text === 2">工资减少项</span>
            </div>
            <div slot="isUse" slot-scope="text, record">
              <a-tooltip>
                <!-- <template slot="title" v-if="record.isDefault === true">
                  该字段默认开启
                </template> -->
                <a-checkbox
                  v-model="record.isUse"
                  @change="checkChange"
                  :disabled="
                    record.name === '应发工资' ||
                      record.name === '实发工资' ||
                      record.name === '个人社保' ||
                      record.name === '企业社保' ||
                      record.name === '个人公积金' ||
                      record.name === '企业公积金' ||
                      record.name === '个人所得税'
                  "
                />
              </a-tooltip>
              <span v-if="record.isDefault === false" class="actionBox">
                <a-icon style="margin-right: 10px" type="form" class="iconStyle" @click="handleEditClick(record)" />
                <a-popconfirm :title="'确定删除' + record.name + '?'" @confirm="handleDeleteClick(record)">
                  <a-icon type="delete" class="iconStyle" />
                </a-popconfirm>
              </span>
            </div>
          </a-table>
        </a-col>
      </a-row>
      <a-row class="file-foot-save" style="display: flex; justify-content: center">
        <a-col class="fr">
          <a-button type="primary" style="margin-bottom: 20px" @click="handleSubmit">保存</a-button>
        </a-col>
      </a-row>
      <a-modal v-model="visible" title="添加自定义项目" width="570px" @ok="handleOk">
        <a-form-model ref="ruleForm" prop="form" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol" style="margin-left: 30px">
          <a-form-model-item
            ref="name"
            label="项目名称"
            prop="name"
            :rules="{
              required: true,
              message: '项目名称必填'
            }"
            style="margin-top: 20px"
          >
            <a-input v-model="form.name" style="margin-left: 15px; width: 300px" placeholder="请输入" />
          </a-form-model-item>
          <a-form-model-item
            ref="mode"
            label="工资加减项"
            prop="mode"
            :rules="{
              required: true,
              message: '工资加减项必选'
            }"
            style="margin-top: 30px"
          >
            <a-radio-group v-model="form.mode" style="margin-left: 20px">
              <a-radio :value="1">工资增加项</a-radio>
              <a-radio :value="2">工资减少项</a-radio>
              <a-radio :value="0">非工资计算项</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item
            ref="isTaxCalculation"
            label="是否计税"
            prop="isTaxCalculation"
            :rules="{
              required: true,
              message: '是否计税必选'
            }"
            style="margin-top: 30px"
          >
            <a-radio-group v-model="form.isTaxCalculation" style="margin-left: 20px">
              <a-radio :value="true">计税</a-radio>
              <a-radio :value="false">不计税</a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-form-model>
        <a-layout />
      </a-modal>
      <a-modal v-model="editVisible" title="编辑自定义项目" width="570px" @ok="handleEditOk">
        <a-form-model
          ref="ruleEditForm"
          prop="editList"
          :model="editList"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          style="margin-left: 30px"
        >
          <a-form-model-item
            ref="name"
            label="项目名称"
            prop="name"
            :rules="{
              required: true,
              message: '项目名称必填'
            }"
            style="margin-top: 20px"
          >
            <a-input @change="inputChange" v-model="editList.name" style="margin-left: 15px; width: 300px" placeholder="请输入" />
          </a-form-model-item>
          <a-form-model-item
            ref="isAdd"
            label="工资加减项"
            prop="isAdd"
            :rules="{
              required: true,
              message: '工资加减项必选'
            }"
            style="margin-top: 30px"
          >
            <a-radio-group v-model="editList.isAdd" style="margin-left: 20px">
              <a-radio :value="1">工资增加项</a-radio>
              <a-radio :value="2">工资减少项</a-radio>
              <a-radio :value="0">非工资计算项</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item
            ref="isTaxCalculation"
            label="是否计税"
            prop="isTaxCalculation"
            :rules="{
              required: true,
              message: '是否计税必选'
            }"
            style="margin-top: 30px"
          >
            <a-radio-group v-model="editList.isTaxCalculation" style="margin-left: 20px">
              <a-radio :value="true">计税</a-radio>
              <a-radio :value="false">不计税</a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-form-model>
        <a-layout />
      </a-modal>
    </a-layout>
  </div>
</template>
<script>
import { getTemplateItems, addTemplateItems, getSalaryTemplates, editTemplateItems } from "@/api/wages/template";
import { isContainByString } from "@/utils/index";
const columns = [
  {
    title: "工资表项目",
    dataIndex: "name",
    key: "name",
    scopedSlots: { customRender: "name" },
    width: 300
  },
  {
    title: "加/减项",
    dataIndex: "isAdd",
    key: "isAdd",
    scopedSlots: { customRender: "isAdd" },
    width: 80
  },
  {
    title: "是否开启",
    key: "isUse",
    scopedSlots: { customRender: "isUse" },
    width: 100
  }
];
export default {
  data() {
    return {
      isContainByString,
      loading: true,
      decimalPlaces: undefined,
      addState: true,
      templateName: "",
      templateId: "",
      salaryTemplateId: "",
      relative: {},
      editList: {},
      inputName: "",
      companyId: this.$store.state.hr.companyId,
      editVisible: false,
      dataList: [],
      columns,
      visible: false,
      form: {},
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      recordKey: null
    };
  },
  created() {
    this.salaryTemplateId = this.$route.query.id;
    this.getSalaryTemplatesList();
  },

  methods: {
    inputChange() {},
    goBack() {
      const _this = this;
      this.$confirm({
        title: "工资表模板尚未保存，是否确认离开？",
        okText: "确定",
        cancelText: "取消",
        onOk() {
          _this.$router.go(-1);
        }
      });
    },
    getSalaryTemplatesList() {
      this.loading = true;
      getSalaryTemplates(this.salaryTemplateId).then(res => {
        this.loading = false;
        this.inputName = res.data.name;
        this.templateId = res.data.id;
        this.decimalPlaces = res.data.decimalPlaces;
        this.dataList = res.data.salaryTemplateItemVOList;
        this.dataList.forEach((item, index) => {
          item.key = index;
        });

        this.dataList.splice(
          this.dataList.length,
          0,
          {
            name: "应发工资",
            isAdd: 0,
            isUse: true,
            isDefault: true
          },
          {
            name: "个人社保",
            isAdd: 0,
            isUse: true,
            isDefault: true
          },
          {
            name: "企业社保",
            isAdd: 0,
            isUse: true,
            isDefault: true
          },
          {
            name: "个人公积金",
            isAdd: 0,
            isUse: true,
            isDefault: true
          },
          {
            name: "企业公积金",
            isAdd: 0,
            isUse: true,
            isDefault: true
          },
          {
            name: "个人所得税",
            isAdd: 0,
            isUse: true,
            isDefault: true
          },
          {
            name: "实发工资",
            isAdd: 0,
            isUse: true,
            isDefault: true
          }
        );
      });
    },
    handleSubmit() {
      if ((this.inputName && this.decimalPlaces) || (this.inputName && this.decimalPlaces === 0)) {
        // var that = this;
        // this.$confirm({
        //   title: "确定修改工资表模板吗？修改后工资表数据将清空",

        //   onOk() {
        var arr = JSON.parse(JSON.stringify(this.dataList));
        arr.splice(arr.length - 7, 7);
        arr.forEach((item, index) => {
          item.sort = index;
        });
        editTemplateItems({
          companyId: this.isContainByString("contractAdmin") ? "0" : this.companyId,
          name: this.inputName,
          id: this.templateId,
          salaryTemplateItemUpdateDTOList: arr,
          decimalPlaces: this.decimalPlaces
        }).then(({ success }) => {
          if (success) {
            history.back();
            this.$notification["success"]({ message: "保存成功" });
          }
        });
        // },
        //   onCancel() {
        //     console.log("Cancel");
        //   }
        // });
      } else if (!this.inputName) {
        this.$notification["error"]({
          message: "error",
          description: "保存失败,模板名称必填"
        });
      } else if (this.decimalPlaces === undefined) {
        this.$notification["error"]({
          message: "error",
          description: "保存失败,尾数处理位数必选"
        });
      }
    },
    handleEditClick(record) {
      this.recordKey = record.key;
      this.editVisible = true;
      // this.$refs.ruleEditForm.resetFields();
      this.editList = JSON.parse(JSON.stringify(record));
    },
    getTemplateItemsList() {
      getTemplateItems().then(res => {
        this.dataList = res.data;
      });
    },
    handleClick() {
      this.visible = true;
      this.form = {};
      this.$refs.ruleForm.resetFields();
    },
    handleOk() {
      this.addState = true;
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.dataList.forEach(item => {
            if (item.name === this.form.name) {
              this.addState = false;
              this.$notification["error"]({
                message: "error",
                description: "工资表项目已有此项目名称"
              });
            }
          });
          if (this.addState === true) {
            this.dataList.splice(this.dataList.length - 7, 0, {
              name: this.form.name,
              isAdd: this.form.mode,
              isUse: true,
              isDefault: false,
              isTaxCalculation: this.form.isTaxCalculation
            });
            this.dataList.forEach((item, index) => {
              this.visible = false;
              item.key = index;
            });
            this.$notification["success"]({
              message: "success",
              description: "添加成功"
            });
          }
        } else {
          return false;
        }
      });
    },
    handleDeleteClick(record) {
      this.dataList.forEach(item => {
        this.dataList = this.dataList.filter(item => item.key !== record.key);
      });
      this.$notification["success"]({
        message: "success",
        description: "删除成功"
      });
    },
    handleEditOk() {
      this.addState = true;
      this.$refs.ruleEditForm.validate(valid => {
        if (valid) {
          this.dataList.forEach((item, index) => {
            if (this.recordKey !== index) {
              if (item.name === this.editList.name) {
                this.addState = false;
                this.$notification["error"]({
                  message: "error",
                  description: "工资表项目已有此项目名称"
                });
              }
            }
          });
          if (this.addState === true) {
            this.dataList.forEach(item => {
              if (item.key === this.editList.key) {
                item.name = JSON.parse(JSON.stringify(this.editList.name));
                item.isAdd = JSON.parse(JSON.stringify(this.editList.isAdd));
                item.isTaxCalculation = JSON.parse(JSON.stringify(this.editList.isTaxCalculation));
                this.editVisible = false;
              }
            });
            this.$notification["success"]({
              message: "success",
              description: "编辑成功"
            });
          } else {
            return false;
          }
        }
      });
    },
    checkChange() {
      this.dataList.forEach(item => {
        if (item.key === this.editList.key) {
          item.isUse = JSON.parse(JSON.stringify(this.editList.isuse));
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
$body-width: calc(100% - 338px);
.head {
  .anticon-left {
    z-index: 3;
    left: 24px;
    position: absolute;
    color: #595959;
    font-size: 20px;
    margin-top: 21px;
  }
  .left2 {
    z-index: 3;
    left: 50px;
    position: absolute;
    color: #595959;
    font-size: 16px;
  }
  font-size: 16px;
  color: #000000;
  font-weight: 500;
  text-align: center;
  line-height: 60px;
  height: 60px;
  border-bottom: 1px solid #e8e8e8;
}
.describeHead {
  padding: 20px;
  padding-bottom: 0;
  .title {
    font-size: 18px;
    color: #252525;
  }
  .font {
    font-size: 14px;
    color: #999999;
  }
}
.inputBox,
.content {
  padding: 20px;
  padding-top: 0;
  font-size: 18px;
  color: #252525;
  .little {
    font-size: 14px;
    color: #999999;
    margin-top: 15px;
  }
  .inpputBoxTitle {
    line-height: 20px;
    height: 20px;
    border-left: 3px solid var(--primary);
    padding-left: 10px;
  }
}
.flexBoxTitle {
  border-left: 3px solid var(--primary);
  padding-left: 10px;
  height: 20px;
  line-height: 20px;
}

.primaryButton {
  margin-bottom: 15px;
}
.actionBox {
  font-size: 16px;
  position: absolute;
  right: 80px;
}
.iconStyle {
  color: var(--primary);
}
</style>
